import axios from 'axios'

// Always use relative base; rely on Vite proxy in dev, and reverse proxy in prod
const api = axios.create({ baseURL: '' })

api.interceptors.request.use((config) => {
  const token = localStorage.getItem('token')
  if (token) config.headers.Authorization = `Bearer ${token}`
  return config
})

// global 401 handler: force re-login
api.interceptors.response.use(
  (res) => res,
  async (error) => {
    if (error?.response?.status === 401) {
      const url = error.config?.url || ''

      // 仅在与认证强相关的接口上清空登录态，避免业务接口偶发 401 把用户直接踢下线
      const shouldClearAuth =
        url.includes('/api/auth/login') ||
        url.includes('/api/users/me')

      if (shouldClearAuth) {
        try {
          const { useAuthStore } = await import('./stores/auth')
          const auth = useAuthStore()
          auth.clear()
        } catch { }
      }

      // 无论是否清空登录态，都统一跳转到登录页，并带上当前路径作为 redirect
      // 但如果是登录接口本身的 401，说明是账号密码错误，不要跳转，否则会死循环
      if (!url.includes('/api/auth/login')) {
        try {
          const routerMod = await import('./router')
          const to = typeof window !== 'undefined' ? window.location.pathname + window.location.search : '/'
          if (routerMod.default?.currentRoute?.value?.name !== 'login') {
            routerMod.default.push({ name: 'login', query: { redirect: to } })
          }
        } catch { }
      }
    }
    return Promise.reject(error)
  }
)

export default api
